package com.mask.im.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.mask.im.business.model.entity.chat.Friendships;
import com.mask.im.business.model.entity.UserInfo;
import com.mask.im.business.common.exception.BusinessException;
import com.mask.im.business.mapper.FriendFeedCommentsMapper;
import com.mask.im.business.mapper.IMFriendDynamicMapper;
import com.mask.im.business.mapper.FriendshipsMapper;
import com.mask.im.business.mapper.UserInfoMapper;
import com.mask.im.business.model.dto.CommentNodeDTO;
import com.mask.im.business.model.dto.FriendFeedDTO;
import com.mask.im.business.model.entity.chat.IMFriendDynamicCommentsDO;
import com.mask.im.business.model.entity.chat.IMFriendDynamicDO;
import com.mask.im.business.model.vo.FriendFeedCommentVO;
import com.mask.im.business.model.vo.PostUpdatesVO;
import com.mask.im.business.common.model.RestResponse;
import com.mask.im.business.service.FriendFeedMessageService;
import com.mask.im.business.service.IMFriendDynamicService;
import com.mask.im.business.common.util.BeanCopy;
import com.mask.im.business.common.util.MaskIMSecurityUtils;
import com.mask.im.business.common.util.PageUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.mask.im.business.common.constant.CommonConstant.*;


/**
 * 用户动态查询
 * @author jian
 */

@Service
public class IMFriendDynamicServiceImpl extends ServiceImpl<IMFriendDynamicMapper, IMFriendDynamicDO> implements IMFriendDynamicService {

	@Autowired
	private FriendshipsMapper friendshipsMapper;

	@Autowired
	private FriendFeedCommentsMapper friendFeedCommentsMapper;

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Autowired
	private FriendFeedMessageService friendFeedMessageService;

	@Override
	public RestResponse<String> PostUpdates(PostUpdatesVO postUpdatesVO) {
		IMFriendDynamicDO imFriendDynamic = BeanCopy.singleCopy(postUpdatesVO, IMFriendDynamicDO.class);
        imFriendDynamic.setUserId(MaskIMSecurityUtils.getUserId());
		boolean save = this.save(imFriendDynamic);
		if (save) {
			return RestResponse.ok();
		}
		return RestResponse.fail();
	}

	@Override
	public RestResponse<List<FriendFeedDTO>> dynamicLists() {
		Long userInfoId = MaskIMSecurityUtils.getUseLongId();
		List<Friendships> friendships = friendshipsMapper.selectList(new LambdaQueryWrapper<Friendships>()
				.select(Friendships::getTwoUserId)
				.eq(Friendships::getOneUserId, userInfoId)
				.eq(Friendships::getIsFriends, TRUE));
		//获取自己好友
		List<Long> twoUserIds = friendships.stream().map(Friendships::getTwoUserId)
				.collect(Collectors.toList());
		//获取自己和好友发表的动态
		twoUserIds.add(userInfoId);
		Page<IMFriendDynamicDO> friendFeedPage = this.baseMapper.selectPage(new Page<>(PageUtil.getLimitPage(), PageUtil.getSize()),
				new LambdaQueryWrapper<IMFriendDynamicDO>()
						.in(IMFriendDynamicDO::getUserId, twoUserIds)
						.orderByDesc(IMFriendDynamicDO::getCreateTime));
		return postposition(friendFeedPage,userInfoId);
	}

	@Override
	public RestResponse<String> friendFeedComment(FriendFeedCommentVO friendFeedCommentVO) {
		Integer userInfoId = MaskIMSecurityUtils.getUserId();
		IMFriendDynamicCommentsDO imFriendDynamicComments = new IMFriendDynamicCommentsDO();
		imFriendDynamicComments.setDynamicId(friendFeedCommentVO.getFriendFeedId());
		imFriendDynamicComments.setCommentContent(friendFeedCommentVO.getCommentContent());
		imFriendDynamicComments.setReplyUserId(friendFeedCommentVO.getReplyUserId());

//		IMFriendDynamicComments friendFeedComments = BeanCopy.singleCopy(friendFeedCommentVO, IMFriendDynamicComments.class);
		imFriendDynamicComments.setCommentUserId(userInfoId);
		int insert = friendFeedCommentsMapper.insert(imFriendDynamicComments);
		IMFriendDynamicDO IMFriendDynamic = this.getById(imFriendDynamicComments.getDynamicId());
		if (!IMFriendDynamic.getUserId().equals(userInfoId) || (Objects.nonNull(friendFeedCommentVO.getReplyUserId()) && !friendFeedCommentVO.getReplyUserId().equals(userInfoId))){
			CompletableFuture.runAsync(()-> friendFeedMessageService.saveFriendFeedMessage(ONE,friendFeedCommentVO.getCommentContent(), IMFriendDynamic.getId(),userInfoId,friendFeedCommentVO.getReplyUserId()));
		}
		if (insert > 0) {
			return RestResponse.ok();
		}
		return RestResponse.fail();
	}

	@Override
	public RestResponse<String> friendFeedLit(Integer friendFeedId) {
		Integer userInfoId = MaskIMSecurityUtils.getUserId();
        IMFriendDynamicDO IMFriendDynamic = this.getById(friendFeedId);
		String lightUpUser = IMFriendDynamic.getLightUpUser();
		if (lightUpUser != null && !lightUpUser.isEmpty()) {
			List<String> list = Arrays.asList(lightUpUser.split(","));
			List<String> objects = new ArrayList<>(list);
			if (!objects.contains(userInfoId.toString())) {
				objects.add(userInfoId.toString());
				String lightUpUsers = StringUtils.join(objects, ",");
				IMFriendDynamic.setLightUpUser(lightUpUsers);
				if (!IMFriendDynamic.getUserId().equals(userInfoId)){
					CompletableFuture.runAsync(()-> friendFeedMessageService.saveFriendFeedMessage(ZERO,null, IMFriendDynamic.getId(),userInfoId,null));
				}

			} else {
				objects.remove(userInfoId.toString());
				String lightUpUsers = StringUtils.join(objects, ",");
				IMFriendDynamic.setLightUpUser(lightUpUsers);
			}
		} else {
			IMFriendDynamic.setLightUpUser(userInfoId.toString());
			if (!IMFriendDynamic.getUserId().equals(userInfoId)){
				CompletableFuture.runAsync(()-> friendFeedMessageService.saveFriendFeedMessage(ZERO,null, IMFriendDynamic.getId(),userInfoId,null));
			}

		}
		this.updateById(IMFriendDynamic);
		return RestResponse.ok();
	}

	@Override
	public RestResponse<FriendFeedDTO> dynamicById(Integer friendFeedId) {
		Integer userInfoId = MaskIMSecurityUtils.getUserId();
        IMFriendDynamicDO IMFriendDynamic = this.getById(friendFeedId);
		FriendFeedDTO friendFeedDTO = BeanCopy.singleCopy(IMFriendDynamic, FriendFeedDTO.class);
		friendFeedDTO.setImageList(new ArrayList<>(Arrays.asList(IMFriendDynamic.getImages().split(",")))
				.stream().filter(s -> s != null && !s.isEmpty())
				.collect(Collectors.toList()));
		friendFeedDTO.setIsLightUp(FALSE);
		//封装用户信息
		if (IMFriendDynamic.getUserId().equals(userInfoId)) {
//			friendFeedDTO.setAvatar(MaskIMSecurityUtils.getUserDetailsDTO().getAvatar());
//			friendFeedDTO.setNickName(MaskIMSecurityUtils.getUserDetailsDTO().getNickName());
		} else {
			Friendships friendItem = friendshipsMapper.selectOne(new LambdaQueryWrapper<Friendships>()
					.eq(Friendships::getOneUserId, userInfoId)
					.eq(Friendships::getTwoUserId, IMFriendDynamic.getUserId()));
			UserInfo userInfo = userInfoMapper.selectById(IMFriendDynamic.getUserId());
			friendFeedDTO.setNickName(friendItem.getRemark());
			friendFeedDTO.setAvatar(userInfo.getAvatar());
		}
		//点亮的用户
		String lightUpUser = IMFriendDynamic.getLightUpUser();
		if (Objects.nonNull(lightUpUser) && !lightUpUser.isEmpty()) {
			List<String> stringList = Arrays.asList(lightUpUser.split(","));
			List<String> LightUpUsers = new ArrayList<>();
			stringList.forEach(twoUserId -> {
				if (!twoUserId.equals(userInfoId.toString())) {
					Friendships selectOne = friendshipsMapper.selectOne(new LambdaQueryWrapper<Friendships>()
							.eq(Friendships::getOneUserId, userInfoId)
							.eq(Friendships::getTwoUserId, twoUserId));
					LightUpUsers.add(selectOne.getRemark());
				} else {
					friendFeedDTO.setIsLightUp(TRUE);
//					LightUpUsers.add(MaskIMSecurityUtils.getUserDetailsDTO().getNickName());
				}

				String litUsersName = StringUtils.join(LightUpUsers, ",");
				friendFeedDTO.setLightUpUserName(litUsersName);
			});
		}
		//评论的用户
		List<IMFriendDynamicCommentsDO> friendFeedComments = friendFeedCommentsMapper.selectList(new LambdaQueryWrapper<IMFriendDynamicCommentsDO>()
				.eq(IMFriendDynamicCommentsDO::getDynamicId, IMFriendDynamic.getId())
				.orderByAsc(IMFriendDynamicCommentsDO::getCreateTime));
		List<CommentNodeDTO> commentNodeDTOS = friendFeedComments.stream().map(friendFeedComment -> {
			CommentNodeDTO commentNodeDTO = new CommentNodeDTO();
			UserInfo userInfo = userInfoMapper.selectById(friendFeedComment.getCommentUserId());
			if (Objects.nonNull(friendFeedComment.getReplyUserId())) {
				UserInfo replyUserId = userInfoMapper.selectById(friendFeedComment.getReplyUserId());
				commentNodeDTO.setReplyUserName(replyUserId.getNickName());
				commentNodeDTO.setReplyUserId(replyUserId.getId());
			}
			commentNodeDTO.setCommentUserName(userInfo.getNickName());
			commentNodeDTO.setCommentUserId(userInfo.getId());
			commentNodeDTO.setCommentContent(friendFeedComment.getCommentContent());
			return commentNodeDTO;
		}).collect(Collectors.toList());
		friendFeedDTO.setCommentNodeDTOS(commentNodeDTOS);
		return RestResponse.ok(friendFeedDTO);
	}

	@Override
	public RestResponse<List<FriendFeedDTO>> ownDynamicsLists() {
		Long userInfoId = MaskIMSecurityUtils.getUseLongId();
		Page<IMFriendDynamicDO> friendFeedPage = this.baseMapper.selectPage(new Page<>(PageUtil.getLimitPage(), PageUtil.getSize()),
				new LambdaQueryWrapper<IMFriendDynamicDO>()
						.eq(IMFriendDynamicDO::getUserId, userInfoId)
						.orderByDesc(IMFriendDynamicDO::getCreateTime));

		return postposition(friendFeedPage,userInfoId);

	}

	@Override
	public RestResponse<String> delMyselfDynamic(Integer id) {
		Integer userInfoId = MaskIMSecurityUtils.getUserId();
        IMFriendDynamicDO IMFriendDynamic = this.getById(id);
		if (!IMFriendDynamic.getUserId().equals(userInfoId)){
			throw new BusinessException("只允许删除自己已发布的动态，删除失败！");
		}
		this.removeById(id);
		return RestResponse.ok();
	}

	private RestResponse<List<FriendFeedDTO>> postposition(Page<IMFriendDynamicDO> pageData, Long userInfoId){
		List<FriendFeedDTO> feedDTOList = pageData.getRecords().stream()
				.filter(IMFriendDynamic -> IMFriendDynamic.getUserId().equals(userInfoId) || IMFriendDynamic.getSeeDetails().equals(ONE))
				.map(item -> {
					FriendFeedDTO friendFeedDTO = BeanCopy.singleCopy(item, FriendFeedDTO.class);
					friendFeedDTO.setImageList(new ArrayList<>(Arrays.asList(item.getImages().split(",")))
							.stream().filter(s -> s != null && !s.isEmpty())
							.collect(Collectors.toList()));
					friendFeedDTO.setIsLightUp(FALSE);
					//封装用户信息
					if (item.getUserId().equals(userInfoId)) {
//						friendFeedDTO.setAvatar(MaskIMSecurityUtils.getUserDetailsDTO().getAvatar());
//						friendFeedDTO.setNickName(MaskIMSecurityUtils.getUserDetailsDTO().getNickName());
					} else {
						Friendships friendItem = friendshipsMapper.selectOne(new LambdaQueryWrapper<Friendships>()
								.eq(Friendships::getOneUserId, userInfoId)
								.eq(Friendships::getTwoUserId, item.getUserId()));
						UserInfo userInfo = userInfoMapper.selectById(item.getUserId());
						friendFeedDTO.setNickName(friendItem.getRemark());
						friendFeedDTO.setAvatar(userInfo.getAvatar());
					}
					//点亮的用户
					String lightUpUser = item.getLightUpUser();
					if (Objects.nonNull(lightUpUser) && !lightUpUser.isEmpty()) {
						List<String> stringList = Arrays.asList(lightUpUser.split(","));
						List<String> LightUpUsers = new ArrayList<>();
						stringList.forEach(twoUserId -> {
							if (!twoUserId.equals(userInfoId.toString())) {
								Friendships selectOne = friendshipsMapper.selectOne(new LambdaQueryWrapper<Friendships>()
										.eq(Friendships::getOneUserId, userInfoId)
										.eq(Friendships::getTwoUserId, twoUserId));
								if (null != selectOne){
									LightUpUsers.add(selectOne.getRemark());
								}
							} else {
								friendFeedDTO.setIsLightUp(TRUE);
//								LightUpUsers.add(MaskIMSecurityUtils.getUserDetailsDTO().getNickName());
							}

							String litUsersName = StringUtils.join(LightUpUsers, ",");
							friendFeedDTO.setLightUpUserName(litUsersName);
						});
					}
					//评论的用户
					List<IMFriendDynamicCommentsDO> friendFeedComments = friendFeedCommentsMapper.selectList(new LambdaQueryWrapper<IMFriendDynamicCommentsDO>()
							.eq(IMFriendDynamicCommentsDO::getDynamicId, item.getId())
							.orderByAsc(IMFriendDynamicCommentsDO::getCreateTime));
					List<CommentNodeDTO> commentNodeDTOS = friendFeedComments.stream().map(friendFeedComment -> {
						CommentNodeDTO commentNodeDTO = new CommentNodeDTO();
						UserInfo userInfo = userInfoMapper.selectById(friendFeedComment.getCommentUserId());
						if (Objects.nonNull(friendFeedComment.getReplyUserId())) {
							UserInfo replyUserId = userInfoMapper.selectById(friendFeedComment.getReplyUserId());
							commentNodeDTO.setReplyUserName(replyUserId.getNickName());
							commentNodeDTO.setReplyUserId(replyUserId.getId());
						}
						commentNodeDTO.setCommentUserName(userInfo.getNickName());
						commentNodeDTO.setCommentUserId(userInfo.getId());
						commentNodeDTO.setCommentContent(friendFeedComment.getCommentContent());
						return commentNodeDTO;
					}).collect(Collectors.toList());
					friendFeedDTO.setCommentNodeDTOS(commentNodeDTOS);
					return friendFeedDTO;
				}).collect(Collectors.toList());
		return RestResponse.ok(feedDTOList);
	}
}

